package com.example.daydayup.tryTest;

/**
 * Description: volatile 关键字
 * 关键字volatile在Java中本质上是一种修饰符，它用来修饰变量。
 * volatile关键字在多线程编程中非常重要，它保证了多个线程之间变量的可见性和有序性。<br/>
 *
 * @author: wells <br/>
 * @since 2024-04-1 20:15
 */
public class VolatileTest {
    // *****volatile
    volatile boolean flag = true;

    public void updateFlag() {
        this.flag = false;
        System.out.println("修改flag值为：" + this.flag);
    }

    public static void main(String[] args) {

        VolatileTest test = new VolatileTest();
        new Thread(() -> {
            while (test.flag) {
                System.out.println("test.flag：" + test.flag);
            }
            System.out.println("test.flag：" + test.flag);
            System.out.println(Thread.currentThread().getName() + "结束");
        }, "Thread1").start();

        new Thread(() -> {
            try {
                Thread.sleep(2000);
                test.updateFlag();
            } catch (InterruptedException e) {
            }
            System.out.println(Thread.currentThread().getName() + "结束");
        }, "Thread2").start();
        System.out.println("程序结束");

    }
}


